package com.rlz.base.event

import androidx.annotation.MainThread
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import com.rlz.libs.log.P
import java.util.concurrent.atomic.AtomicBoolean

/**
 * Created by RLZ
 * on 2021/10/18
 *
 *  这是一个只会发送一次更新的 LiveData。
 */
class SingleEvent<T> : MutableLiveData<T>() {

    private val mAwait = AtomicBoolean(false)

    @MainThread
    fun onObserve(owner: LifecycleOwner, observer: Observer<T?>) {
        if (hasActiveObservers()) {
            P.w(javaClass.name, "无论多少个观察者,只会有一个被通知")
        }

        super.observe(owner, { t: T ->
            if (mAwait.compareAndSet(true, false)) {
                observer.onChanged(t)
            }
        })
    }

    @MainThread
    override fun setValue(value: T?) {
        mAwait.set(true)
        super.setValue(value)
    }

    @MainThread
    fun call() {
        value = null
    }
}